import { observable, action } from 'mobx';
import { WeaForm } from 'comsMobx';
import { WeaTools , WeaLocaleProvider} from 'ecCom';
import * as API from '../apis/customQuery';
const getLabel = WeaLocaleProvider.getLabel;
const Base64 = WeaTools.Base64;

export class WFQueryIndexStore {
    
    @observable loading = false;
    title;
    @observable belongPathTree = true;
    showTreeSwitch = true;
    urlParams = {};
    wfBrowserLimit = {};
    @observable treeProps = {};
    fixedCondition = [];
    customid = "";
    operBtnKey = "";
    @observable customOption = [];
    customCondition = [];
    @observable fixedForm = new WeaForm();
    @observable customForm = null;
    @observable showSearchAd = false;
    loadCustomConditionCallback = null;

    constructor(){
        this.setLoading = this.setLoading.bind(this);
        this.setUrlParams = this.setUrlParams.bind(this);
        this.setShowTreeSwitch = this.setShowTreeSwitch.bind(this);
        this.doInit = this.doInit.bind(this);
        this.initTreeProps = this.initTreeProps.bind(this);
        this.switchTreeType = this.switchTreeType.bind(this);
        this.loadTree = this.loadTree.bind(this);
        this.showAllTreeNode = this.showAllTreeNode.bind(this);
        this.setSelectedTreeKey = this.setSelectedTreeKey.bind(this);
        this.setConditionByTree = this.setConditionByTree.bind(this);
        this.setShowSearchAd = this.setShowSearchAd.bind(this);
        this.loadFixedCondition = this.loadFixedCondition.bind(this);
        this.appendFixedFormFields = this.appendFixedFormFields.bind(this);
        this.changeWorkflowid = this.changeWorkflowid.bind(this);
        this.changeCustomid = this.changeCustomid.bind(this);
        this.loadCustomCondition = this.loadCustomCondition.bind(this);
        this.resetCondition = this.resetCondition.bind(this);
        this.clearCustomCondition = this.clearCustomCondition.bind(this);
    }

    @action
    setLoading(bool = false){
        this.loading = bool;
    }

    setUrlParams(params = {}){
        this.urlParams = params;
        this.title = getLabel(386385,"查询流程");
        if(this.urlParams.tabTitle){
            this.title = Base64.decode(decodeURIComponent(this.urlParams.tabTitle));
        }
        if(this.urlParams.rejectType == '0'){
            this.title = getLabel(517344, '退回给我');
        }else if(this.urlParams.rejectType == '1'){
          this.title = getLabel(516707,'被我退回');
      }
    }

    setShowTreeSwitch(bool = true){
        this.showTreeSwitch = bool;
    }

    doInit(callbackFun){
        if(this.urlParams.isPreview === "true")
            this.belongPathTree = false;
        else
            this.belongPathTree = true;
        if(this.urlParams.needTree !== "false"){
            this.initTreeProps();
            this.loadTree();
        }
        this.resetCondition(true);
        this.loadFixedCondition(callbackFun);
    }

    initTreeProps(){
        this.treeProps = {
            option : [{key:"path",name:getLabel(386386,"按流程类型显示")},{key:"kind",name:getLabel(23802,"按查询种类显示")}],
            pathTree : WeaTools.ls.getJSONObj("WfQueryPathTree") || [],
            kindTree : WeaTools.ls.getJSONObj("WfQueryKindTree") || [],
            selectedKey : ""
        }
    }

    switchTreeType(type){
        this.treeProps.selectedKey = "";
        this.belongPathTree = (type === "path");
        this.loadTree();
        this.wfBrowserLimit = {};
        this.clearCustomCondition(true);
        if(type === "kind"){    //切换种类树，清空类型及路径条件
            this.clearFixedFormField("typeid");
        }
    }

    loadTree(){
        this.treeProps.selectedKey = "";
        //if(!mustLoad && ((this.belongPathTree && this.treeProps.pathTree.length > 0) || (!this.belongPathTree && this.treeProps.kindTree.length > 0)))
        //    return;
        this.loading = true;
        let params = {...{belongPathTree:this.belongPathTree},...this.urlParams};
        const allowRange = ["jsonstr", "offical", "officalType","eid","tabid"];
        allowRange.map(v=>{
            if(v in this.urlParams)
                params[v] = this.urlParams[v];
        });
        API.getQueryTree(params).then(datas =>{
            if(this.belongPathTree){
                this.treeProps.pathTree = datas.tree;
                WeaTools.ls.set("WfQueryPathTree", datas.tree);
            }else{
                this.treeProps.kindTree = datas.tree;
                WeaTools.ls.set("WfQueryKindTree", datas.tree);
            }
            this.loading = false;
        });
    }

    showAllTreeNode(){
        this.loadTree();
    }

    setSelectedTreeKey(key, fun){
        this.treeProps.selectedKey = key;
        this.loadCustomConditionCallback = fun;
        if(this.belongPathTree){
            this.setConditionByTree(key);
            if(key.indexOf("wf_") > -1){
                this.changeWorkflowid(key.substring(3));
            }else{
                this.clearCustomCondition(true);
                if(typeof this.loadCustomConditionCallback === "function")
                    this.loadCustomConditionCallback();
            }
        }else{
            if(key.indexOf("wf_") > -1){
                this.changeCustomid(key.substring(3));
            }
        }
    }

    setConditionByTree(){
        const key = this.treeProps.selectedKey;
        if(this.belongPathTree && !!key){
            let formValues = {};
            if(key.indexOf("type_") > -1){
                const typeid = key.substring(5);
                let typename = '';
                this.treeProps && this.treeProps.pathTree.map(t =>{
                    if(t.domid === key)
                        typename = t.name;
                });
                formValues["typeid"] = {value:typeid, valueSpan:typename};
                formValues["workflowid"] = {value:""};
            }else if(key.indexOf("wf_") > -1){
                const workflowid = key.substring(3);
                let workflowname = '';
                this.treeProps && this.treeProps.pathTree.map(t =>{
                    t.childs && t.childs.map(w =>{
                        if(w.domid === key)
                            workflowname = w.name;
                    });
                });
                formValues["typeid"] = {value:""};
                formValues["workflowid"] = {value:workflowid, valueObj:[{id:workflowid, name:workflowname}]};
            }
            this.appendFixedFormFields(formValues);
        }
    }

    setShowSearchAd(bool) {
        this.showSearchAd = bool;
    }

    loadFixedCondition(callbackFun){
        API.getFixedCondition().then(datas =>{
            this.fixedCondition = datas.condition;
            this.operBtnKey = datas.operBtnKey || "batchShare";
            this.fixedForm.initFormFields(datas.condition);
            //从url参数提取参数赋值
            let formValues = {};
            const supportUrlParams = ["requestname", "workflowid","docids"];
            supportUrlParams.map(k=>{
                if(k in this.urlParams){
                    const value = this.urlParams[k];
                    let valueObj = null;
                    if(k === "workflowid" && "workflowidspan" in this.urlParams)
                        valueObj = [{id:this.urlParams.workflowid, name:this.urlParams.workflowidspan}];
                    if (k === "docids" && "docidsspan" in this.urlParams)
                        valueObj = [{ id: this.urlParams.docids, name: this.urlParams.docidsspan}];
                    formValues[k] = {value,valueObj};
                }
            });
            this.appendFixedFormFields(formValues);
            if(typeof callbackFun === "function")
                callbackFun();
        });
    }

    clearFixedFormField(key){
        let formValues = {};
        formValues[key] = {value:""}
        this.appendFixedFormFields(formValues);
    }

    appendFixedFormFields(value){
        this.fixedForm.updateFields(value, false);
    }

    changeWorkflowid(workflowid=""){
        if(this.belongPathTree){
            if(workflowid === "" || workflowid.indexOf(",") > -1)   //多个工作流也不加载自定义条件
                this.clearCustomCondition(true);
            else
                this.loadCustomCondition({source:"changeWf", workflowid});
        }
    }

    changeCustomid(customid=""){
        const workflowid = this.fixedForm && this.fixedForm.getFormParams().workflowid || "";
        this.customid = customid;
        this.loadCustomCondition({source:"changeCustomid", customid, workflowid});
    }

    loadCustomCondition(params){
        this.loading = true;
        const source = params.source;
        this.customForm = new WeaForm();
        API.getCustomCondition(params).then(data =>{
            //加载后的workflowid与当前不一致的情况直接return，解决快速点击异常问题
            if(source === "changeWf"){
                const fixedSearchParams = this.fixedForm ? this.fixedForm.getFormParams() : {};
                if(params.workflowid != fixedSearchParams.workflowid)
                    return;
            }else if(source === "changeCustomid"){
                if(params.customid != this.customid)
                    return;
            }
            this.loading = false;
            if(data.customid === ""){   //未设置自定义查询，清空
                this.clearCustomCondition(true);
            }else{
                this.customid = data.customid;
                this.wfBrowserLimit = {formid:data.formid, isbill:data.isbill, wfRanges:data.wfRanges};
                //必须先new WeaForm()，再set条件，再做初始化
                this.customCondition = data.customCondition;
                this.customForm.initFormFieldObj(data.customCondition);
                if((this.belongPathTree && source === "changeWf") || (!this.belongPathTree && source === "changeCustomid"))
                    this.customOption = data.customOption;
                if(!this.belongPathTree && data.needClearWf === true)
                    this.clearFixedFormField("workflowid");
            }
            //结果页点击左侧树同时要做查询,必须是加载完自定义条件后再调用
            if(typeof this.loadCustomConditionCallback === "function")
                this.loadCustomConditionCallback();
        });
    }

    resetCondition(reset = false){
        let resetCustom = reset;
        if(reset){
            this.fixedForm = new WeaForm();
            this.fixedCondition = [];
        }else{
            if(this.belongPathTree){    //当前为路径树，重置直接清空路径条件及树选中状态
                resetCustom= true;
                this.treeProps.selectedKey = "";
            }
            this.fixedForm && this.fixedForm.resetConditionValue();
        }
        this.clearCustomCondition(resetCustom);
    }

    clearCustomCondition(reset = false){
        if(reset){
            this.customForm = null;
            this.customid = "";
            this.customOption = [];
            this.customCondition = [];
            this.wfBrowserLimit = {};
        }else{
            this.customForm && this.customForm.resetConditionValue();
        }
    }

    clearStatus(){
        this.title = getLabel(386385,'查询流程');
        this.urlParams = {};
    }

}